package com.h2cloud.redisTest.testLock;

/**
 * @Package: com.h2cloud.redisTest.testLock
 * @ClassName: ReentrantLockExample
 * @Author: h2cloud
 * @CreateTime: 2023/8/3 9:48 下午
 * @Description:
 */
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

public class ReentrantLockExample {

	private static final ThreadLocal<String> lockHolder = new ThreadLocal<>();

	public static void main(String[] args) {
		// 初始化RedissonClient，这里使用本地单节点的Redis配置
		Config config = new Config();
		config.useSingleServer().setAddress("redis://127.0.0.1:6379");
		RedissonClient redisson = Redisson.create(config);

		try {
			// 在A方法里面获取锁
			String lockKey = "myLock";
			RLock lock = redisson.getLock(lockKey);
			lock.lock();
			System.out.println("A方法获取锁成功");

			// 在A方法内调用B方法
			callBMethod(redisson, lockKey);

		} finally {
			// 释放锁
			RLock lock = redisson.getLock("myLock");
			lock.unlock();
			System.out.println("A方法释放锁成功");
		}

		// 关闭RedissonClient
		redisson.shutdown();
	}

	private static void callBMethod(RedissonClient redisson, String lockKey) {
		// 获取当前线程的标识，可以是线程ID或其他唯一标识
		String currentThreadIdentifier = String.valueOf(Thread.currentThread().getId());

		// 获取锁并执行B方法逻辑
		RLock lock = redisson.getLock(lockKey);
		lock.lock();
		System.out.println("B方法获取锁成功");
		try {
			// 设置当前线程为锁的拥有者
			lockHolder.set(currentThreadIdentifier);
			// TODO: 执行B方法的业务逻辑
		} finally {
			// 释放锁并清除线程标识
			lock.unlock();
			lockHolder.remove();
			System.out.println("B方法释放锁成功");
		}
	}
}

